package be.vdab.servlets;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import be.vdab.DAO.PizzaDAO;
import be.vdab.entities.Pizza;

/**
 * Servlet implementation class PizzaToevoegenServlet
 */
@WebServlet("/pizzas/toevoegen.htm")
@MultipartConfig
public class PizzaToevoegenServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final String VIEW =  "/WEB-INF/JSP/pizzatoevoegen.jsp";
	private static final String REDIRECT_URL = "/pizzas";
	private final PizzaDAO pizzaDAO = new PizzaDAO();

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		RequestDispatcher dispatcher = request.getRequestDispatcher(VIEW);
		dispatcher.forward(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Map<String, String> fouten = new HashMap<>();
		String naam = request.getParameter("naam");
		if (naam == null || naam.isEmpty()) {
			fouten.put("naam", "verplicht");
		}
		BigDecimal prijs = null;
		try {
			prijs = new BigDecimal(request.getParameter("prijs"));
			if (prijs.compareTo(BigDecimal.ZERO) < 1) {
				fouten.put("prijs", "tik een positief getal");
			}
		}catch (Exception ex) {
			fouten.put("prijs", "tik een getal");
		}
		boolean pikant = "pikant".equals(request.getParameter("pikant"));
		Part fotoPart = request.getPart("foto");
		if (fotoPart !=null && fotoPart.getSize() !=0) {
			String contentType = fotoPart.getContentType();
			if (!"image/jpeg".equals(contentType) && ! "image/pjpeg".equals(contentType)) {
				fouten.put("foto", "geen JPEG foto");
			}
		}
		if (fouten.isEmpty()) {
			Pizza pizza = new Pizza(naam, prijs,pikant);
			pizzaDAO.create(pizza);
			if (fotoPart !=null) {
				String pizzaFotosPad = 
						this.getServletContext().getRealPath("/pizzafotos");
				fotoPart.write(pizzaFotosPad + "/" + pizza.getNummer() + ".jpg");
			}
			response.sendRedirect(response.encodeRedirectURL(request.getContextPath() + REDIRECT_URL));
		} else {
			request.setAttribute("fouten", fouten);
			RequestDispatcher dispatcher = request.getRequestDispatcher(VIEW);
			dispatcher.forward(request, response);
		}
	}
}
